var submit = 2
layui.use(['layer', 'form', 'table', 'ztree', 'laydate', 'admin', 'ax'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;

    var layer = layui.layer;
    var $ZTree = layui.ztree;
    var laydate = layui.laydate;

    /**
     * 收货单位表管理
     */
    var BasicPutgoods = {
        tableId: "basicPutgoodsTable",    //表格id
        condition: {
            dictId: "",
        }
    };

    /**
     * 往来地址表管理
     */
    var BasicAddress = {
        tableId: "basicAddressTable"
    };

    /**
     * 初始化表格的列
     */
    BasicPutgoods.initColumn = function () {
        return [[
            {type: 'checkbox'},
            // {align: 'center',width: 120, toolbar: '#tableBar', title: '操作'},
            {field: 'id', title: '单位ID'},
            {field: 'putgoodsOperateName', title: '客户名称'},
            {field: 'putgoodsName', title: '单位名称', style:'font-weight: 600;'},
            {field: 'unitNumber', title: '单位编号', style:'font-weight: 600;'},
            {field: 'putgoodsNotes', title: '配送注意事项'},
            {field: 'helpCode', title: '助记码'},
            {field: 'unitCategory', title: '单位类别'},
            {field: 'unitType', title: '单位类型'},
            {field: 'xlbClientId', title: '新零帮id'},
            {field: 'createTime', title: '创建时间'},
        ]];
    };

    /**
     * 选择时
     */
    BasicPutgoods.onClickDept = function (e, treeId, treeNode) {
        BasicPutgoods.condition.dictId = treeNode.id;
        BasicPutgoods.search();
    };

    /**
     * 点击查询按钮
     */
    BasicPutgoods.search = function () {
        var queryData = {};
        queryData['dictId'] = BasicPutgoods.condition.dictId;
        queryData['condition'] = $("#condition").val();
        queryData['id'] = $("#id").val();
        queryData['unitNumber'] = $("#unitNumber").val();
        queryData['unitType'] = $("#unitType option:selected").html();
        table.reload(BasicPutgoods.tableId, {
            where: queryData, page: {curr: 1},
            done:function () {
            }
        });
    };

    // 导入
    $('#btnExpimporthx').click(function () {
        layer.open({
            type: 2,
            title: '单位地址导入',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPutgoods/toimportExcelhx',
            end: function () {
                table.reload(BasicPutgoods.tableId);
            }
        });
    });

    //拉取新零帮门店
    $('#pullxlbStore').click(function () {
        submit = 2
        layer.open({
            type: 2,
            title: '拉取新零帮门店',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPutgoods/topullxlbStore',
            end: function () {
                if(submit == 1){
                    table.reload(BasicPutgoods.tableId);
                }
            }
        });
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        layer.open({
            type: 2,
            title: '新增客户',
            area: ['900px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPutgoods/add_hx',
            end: function () {
                table.reload(BasicPutgoods.tableId);
            }
        });
    });

    /**
     * 导出excel按钮
     */
    BasicPutgoods.exportExcel = function () {
        var checkRows = table.checkStatus(BasicPutgoods.tableId);
        if (checkRows.data.length > 0) {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        } else {
            window.location.href = Feng.ctxPath + '/basicPutgoods/exportExcelBySpec?dictId='+BasicPutgoods.condition.dictId
                +"&condition="+$("#condition").val()+"&id="+$("#id").val()
                +"&unitNumber="+$("#unitNumber").val()+"&unitType="+$("#unitType option:selected").html();
        }
    };

    /**
     * 点击删除
     * @param data 点击按钮时候的行数据
     */
    BasicPutgoods.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/basicPutgoods/delete", function (data) {
                if(data.success){
                    Feng.success("删除成功!");
                    table.reload(BasicPutgoods.tableId);
                } else {
                    Feng.error("删除失败!" + data.message + "!");
                }
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + BasicPutgoods.tableId,
        url: Feng.ctxPath + '/basicPutgoods/list_hx',
        page: true,
        limit: 60,
        limits:[60,120,240,360,480,600],
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        height: 400,
        cellMinWidth: 100,
        cols: BasicPutgoods.initColumn()
    });

    //初始化左侧部门树
    var ztree = new $ZTree("deptTree", "/hxBasicUnitCode/treeo?v1="+$("#unitType").val());
    ztree.bindOnClick(BasicPutgoods.onClickDept);
    ztree.init();

    //选择单位类型时
    form.on('select(unitType)',function(){
        //初始化左侧部门树
        var ztree = new $ZTree("deptTree", "/hxBasicUnitCode/treeo?v1="+$("#unitType").val());
        ztree.bindOnClick(BasicPutgoods.onClickDept);
        ztree.init();

        BasicPutgoods.condition.dictId = "";
        BasicPutgoods.search();

        form.render('select');
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        BasicPutgoods.search();
    });

    // 导出excel
    $('#btnExp').click(function () {
        BasicPutgoods.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + BasicPutgoods.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            layer.open({
                type: 2,
                title: '编辑客户',
                area: ['900px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/basicPutgoods/edit_hx?id=' + data.id,
                end: function () {
                    table.reload(BasicPutgoods.tableId);
                }
            });
        } else if (layEvent === 'delete') {
            BasicPutgoods.onDeleteItem(data);
        }
    });

    /**
     * 初始化 详细地址  表格的列
     */
    BasicAddress.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {align: 'center',width: 120, toolbar: '#tableBarAddress', title: '操作'},
            {field: 'warehouseOperateName', title: '项目部'},
            {field: 'warehouseName', title: '仓库名称'},
            {field: 'warehouseTypes', title: '仓储类型'},
            {field: 'warehouseType', title: '仓库类型'},
            {field: 'warehouseNumber', title: '仓库编号', sort: true},
            {field: 'warehouseContacts', title: '联系人'},
            {field: 'tel', title: '联系电话'},
            {field: 'warehouseAddress', title: '详细地址'},
            {field: 'longitude', title: '经度'},
            {field: 'latitude', title: '维度'},
            {field: 'warehouseCanmeasure', title: '可用面积', sort: true},
            {field: 'warehouseMeasure', title: '面积', sort: true},
            {field: 'warehouseNotes', title: '备注'},
            {field: 'createTime', sort: true, title: '创建时间'},
            {field: 'warehouseXlbId', sort: true, title: '新零帮仓库id'},
        ]];
    };

    // 单击行事件
    table.on('row(' + BasicPutgoods.tableId + ')', function (obj) {
        var data = obj.data;
        $('div[lay-id="' + BasicPutgoods.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
        $('div[lay-id="' + BasicPutgoods.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        address(data);
    });

    $('#weChat').click(function () {
        layer.open({
            type: 2,
            title: '收货单位微信注册码',
            area: ['1000px', '550px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPutgoods/toqrCode',
            end: function () {
            }
        });
    });

    function address(data){
        var putgoodsId;
        var condition = '';
        if (data!=null) {
            $("#putgoodsId").val(data.id);
            putgoodsId = data.id;
        } else {
            putgoodsId = 0;
            condition = 'ndate';
        }
        // 渲染表格
        var tableResult = table.render({
            elem: '#' + BasicAddress.tableId,
            url: Feng.ctxPath + '/basicWarehouse/getWarehouseByStoreId?storeId='+putgoodsId+'&page=1&limit=100',
            page: true,
            limit: 20,
            height: 370,
            toolbar: '#toolbarfromAddress',
            cellMinWidth: 100,
            cols: BasicAddress.initColumn()
        });

        // 添加按钮点击事件
        $('#btnAddAddress').click(function () {
            layer.open({
                type: 2,
                title: '绑定仓库',
                area: ['900px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/basicWarehouse/add_warehouse?storeId='+putgoodsId,
                end: function () {
                    address(data);
                }
            });
        });

        /**
         * 点击编辑
         *
         * @param data 点击按钮时候的行数据
         */
        BasicAddress.openEditDlg = function (data2) {
            layer.open({
                type: 2,
                title: '修改地址',
                area: ['1000px', '800px'],
                anim: 5,
                content: Feng.ctxPath + '/basicAddress/edit?id='+data2.id,
                end: function () {
                    address(data);
                }
            });
        };

        /**
         * 点击删除
         *
         * @param data 点击按钮时候的行数据
         */
        BasicAddress.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/basicAddress/delete", function (data2) {
                    console.log(data2)
                    if(data2.success){
                        Feng.success("删除成功!");
                        address(data);
                    } else {
                        Feng.error("删除失败!" + data2.message + "!");
                    }
                }, function (data2) {
                    Feng.error("删除失败!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("是否删除?", operation);
        };

        BasicAddress.onUnbind = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/basicPutgoods/onUnbind", function (data2) {
                    console.log(data2)
                    if(data2.success){
                        Feng.success("解绑成功!");
                        address(data);
                    } else {
                        Feng.error("解绑失败!" + data2.message + "!");
                    }
                }, function (data2) {
                    Feng.error("解绑失败!" + data2.responseJSON.message + "!");
                });
                ajax.set("storeId", data2.storeId);
                ajax.set("warehouseId", data2.id);
                ajax.start();
            };
            Feng.confirm("是否解绑?", operation);
        };

        // 工具条点击事件
        table.on('tool(' + BasicAddress.tableId + ')', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;
            if (layEvent === 'unbind') {
                BasicAddress.onUnbind(data);
            }
        });

        // 修改参数状态
        form.on('switch(switchWl)', function (obj) {
            var id = obj.elem.value;
            var checked = obj.elem.checked ? true : false;

            BasicAddress.changeGradingStatus(id, checked);
        });

        /**
         * 修改参数状态
         *
         * @param id 参数id
         * @param checked 是否选中（true,false），选中就是启用用户，未选中就是禁用用户
         */
        BasicAddress.changeGradingStatus = function (id, checked) {
            if (checked) {
                var ajax = new $ax(Feng.ctxPath + "/basicAddress/editItemswitchWl", function (data2) {
                    Feng.success("启用成功!");
                }, function (data) {
                    Feng.error("启用失败!");
                    address(data);
                });
                ajax.set("switchWl", 1);
                ajax.set("id", id);
                ajax.start();
            } else {
                var ajax = new $ax(Feng.ctxPath + "/basicAddress/editItemswitchWl", function (data2) {
                    Feng.success("禁用成功!");
                }, function (data) {
                    Feng.error("禁用失败!" + data.responseJSON.message + "!");
                    address(data);
                });
                ajax.set("switchWl", 2);
                ajax.set("id", id);
                ajax.start();
            }
        };
    }

});
